#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试数据生成器
生成各种类型的测试数据用于验证审核系统
"""

import json
import random
import time
from typing import List, Dict

class TestDataGenerator:
    """测试数据生成器"""
    
    def __init__(self):
        # 正常内容模板
        self.normal_contents = [
            "今天天气真好，适合出去散步",
            "分享一道美味的家常菜做法",
            "最近读了一本很有趣的书",
            "校园生活的一些感悟和体会",
            "学习心得分享，希望对大家有帮助",
            "周末去了一个很美的地方旅游",
            "推荐一部很棒的电影给大家",
            "运动健身的一些小技巧",
            "摄影作品分享，记录美好时光",
            "音乐推荐，最近喜欢的几首歌"
        ]
        
        # 违规内容模板
        self.violation_contents = {
            "sensitive_words": [
                "杀人放火抢劫银行",
                "吸毒贩毒制毒",
                "诈骗传销洗钱",
                "爆炸恐怖袭击",
                "政治敏感内容推翻政府"
            ],
            "spam": [
                "免费领取iPhone15，限时优惠，先到先得！！！",
                "点击链接领取红包，转发朋友圈即可获得现金奖励",
                "加微信获取更多优惠信息，机会难得不要错过",
                "投资理财高收益，月入过万不是梦，快来咨询",
                "减肥神器，一周瘦20斤，无效退款"
            ],
            "advertisement": [
                "超级大促销，全场五折，买一送一",
                "新店开业，所有商品特价销售",
                "品牌代购，正品保证，价格优惠",
                "招聘兼职，在家就能赚钱，日薪300+",
                "培训课程，包教包会，100%就业"
            ],
            "inappropriate": [
                "约炮一夜情刺激",
                "色情内容不当信息",
                "暴力血腥恐怖内容",
                "赌博博彩违法活动",
                "仇恨言论歧视内容"
            ]
        }
        
        # 标题模板
        self.normal_titles = [
            "分享生活感悟",
            "美食制作心得",
            "读书笔记分享",
            "旅游见闻",
            "学习经验交流",
            "摄影作品展示",
            "音乐推荐",
            "运动健身心得",
            "电影观后感",
            "日常生活记录"
        ]
        
        self.violation_titles = [
            "震惊！你绝对想不到的秘密",
            "不看后悔一辈子的内容",
            "免费领取，限时优惠",
            "月入十万的秘密方法",
            "一夜暴富的机会来了"
        ]
        
        # 图片URL列表
        self.image_urls = [
            "https://codefather.cn/logo.png",
            "https://example.com/image1.jpg",
            "https://example.com/image2.png",
            "https://example.com/image3.gif"
        ]
    
    def generate_normal_post(self, post_id: int = None) -> Dict:
        """生成正常帖子"""
        if post_id is None:
            post_id = random.randint(1000, 9999)
        
        return {
            "post_id": post_id,
            "title": random.choice(self.normal_titles),
            "content": random.choice(self.normal_contents),
            "author_id": random.randint(1, 100),
            "images": random.choices(self.image_urls, k=random.randint(0, 2)),
            "timestamp": time.time(),
            "expected_result": "PASS"
        }
    
    def generate_violation_post(self, violation_type: str = None, post_id: int = None) -> Dict:
        """生成违规帖子"""
        if post_id is None:
            post_id = random.randint(1000, 9999)
        
        if violation_type is None:
            violation_type = random.choice(list(self.violation_contents.keys()))
        
        return {
            "post_id": post_id,
            "title": random.choice(self.violation_titles),
            "content": random.choice(self.violation_contents[violation_type]),
            "author_id": random.randint(1, 100),
            "images": random.choices(self.image_urls, k=random.randint(0, 1)),
            "timestamp": time.time(),
            "expected_result": "REJECT",
            "violation_type": violation_type
        }
    
    def generate_mixed_post(self, post_id: int = None) -> Dict:
        """生成混合内容帖子（正常+轻微违规）"""
        if post_id is None:
            post_id = random.randint(1000, 9999)
        
        normal_content = random.choice(self.normal_contents)
        violation_content = random.choice(self.violation_contents["spam"])
        
        # 混合内容
        mixed_content = f"{normal_content}。{violation_content}"
        
        return {
            "post_id": post_id,
            "title": random.choice(self.normal_titles),
            "content": mixed_content,
            "author_id": random.randint(1, 100),
            "images": random.choices(self.image_urls, k=random.randint(0, 1)),
            "timestamp": time.time(),
            "expected_result": "MANUAL"  # 可能需要人工审核
        }
    
    def generate_edge_case_post(self, case_type: str, post_id: int = None) -> Dict:
        """生成边界情况帖子"""
        if post_id is None:
            post_id = random.randint(1000, 9999)
        
        base_post = {
            "post_id": post_id,
            "author_id": random.randint(1, 100),
            "images": [],
            "timestamp": time.time()
        }
        
        if case_type == "empty":
            base_post.update({
                "title": "",
                "content": "",
                "expected_result": "REJECT"
            })
        elif case_type == "very_long":
            base_post.update({
                "title": "很长的标题" * 50,
                "content": "很长的内容" * 200,
                "expected_result": "PASS"
            })
        elif case_type == "special_chars":
            base_post.update({
                "title": "特殊字符测试!@#$%^&*()",
                "content": "测试特殊字符：!@#$%^&*()_+{}|:<>?[]\\;'\",./ 中文测试",
                "expected_result": "PASS"
            })
        elif case_type == "numbers_only":
            base_post.update({
                "title": "1234567890",
                "content": "1234567890 0987654321 数字测试",
                "expected_result": "PASS"
            })
        elif case_type == "english":
            base_post.update({
                "title": "English Test Title",
                "content": "This is an English content test with mixed languages 中英文混合测试",
                "expected_result": "PASS"
            })
        
        return base_post
    
    def generate_batch_data(self, count: int = 100) -> List[Dict]:
        """批量生成测试数据"""
        test_data = []
        
        # 70% 正常内容
        normal_count = int(count * 0.7)
        for i in range(normal_count):
            test_data.append(self.generate_normal_post(i + 1))
        
        # 20% 违规内容
        violation_count = int(count * 0.2)
        for i in range(violation_count):
            test_data.append(self.generate_violation_post(post_id=normal_count + i + 1))
        
        # 5% 混合内容
        mixed_count = int(count * 0.05)
        for i in range(mixed_count):
            test_data.append(self.generate_mixed_post(post_id=normal_count + violation_count + i + 1))
        
        # 5% 边界情况
        edge_count = count - normal_count - violation_count - mixed_count
        edge_types = ["empty", "very_long", "special_chars", "numbers_only", "english"]
        for i in range(edge_count):
            edge_type = edge_types[i % len(edge_types)]
            test_data.append(self.generate_edge_case_post(
                edge_type, 
                post_id=normal_count + violation_count + mixed_count + i + 1
            ))
        
        return test_data
    
    def save_test_data(self, data: List[Dict], filename: str = "test_data.json"):
        """保存测试数据到文件"""
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        print(f"✅ 测试数据已保存到: {filename}")
    
    def load_test_data(self, filename: str = "test_data.json") -> List[Dict]:
        """从文件加载测试数据"""
        try:
            with open(filename, 'r', encoding='utf-8') as f:
                data = json.load(f)
            print(f"✅ 测试数据已从 {filename} 加载，共 {len(data)} 条")
            return data
        except FileNotFoundError:
            print(f"❌ 文件 {filename} 不存在")
            return []
        except Exception as e:
            print(f"❌ 加载测试数据失败: {e}")
            return []


def main():
    """主函数"""
    import argparse
    
    parser = argparse.ArgumentParser(description="测试数据生成器")
    parser.add_argument("--count", type=int, default=100, help="生成数据数量")
    parser.add_argument("--output", default="test_data.json", help="输出文件名")
    parser.add_argument("--type", choices=["normal", "violation", "mixed", "edge", "batch"], 
                       default="batch", help="生成数据类型")
    
    args = parser.parse_args()
    
    generator = TestDataGenerator()
    
    if args.type == "normal":
        data = [generator.generate_normal_post(i) for i in range(1, args.count + 1)]
    elif args.type == "violation":
        data = [generator.generate_violation_post(post_id=i) for i in range(1, args.count + 1)]
    elif args.type == "mixed":
        data = [generator.generate_mixed_post(i) for i in range(1, args.count + 1)]
    elif args.type == "edge":
        edge_types = ["empty", "very_long", "special_chars", "numbers_only", "english"]
        data = []
        for i in range(args.count):
            edge_type = edge_types[i % len(edge_types)]
            data.append(generator.generate_edge_case_post(edge_type, i + 1))
    else:  # batch
        data = generator.generate_batch_data(args.count)
    
    # 保存数据
    generator.save_test_data(data, args.output)
    
    # 显示统计信息
    print(f"\n📊 生成数据统计:")
    print(f"总数量: {len(data)}")
    
    # 按预期结果分类统计
    result_stats = {}
    for item in data:
        result = item.get('expected_result', 'unknown')
        result_stats[result] = result_stats.get(result, 0) + 1
    
    for result, count in result_stats.items():
        percentage = count / len(data) * 100
        print(f"{result}: {count} ({percentage:.1f}%)")


if __name__ == "__main__":
    main()
